package com.zxy.leetcode._00000_00099._00060_00069;

/**
 * https://leetcode-cn.com/problems/sqrtx/
 *
 * x 的平方根
 *
 * 标签：二分查找
 */
public class Test00069 {

    public static void main(String[] args) {
        Test00069 test = new Test00069();
        System.out.println(Math.sqrt(Integer.MAX_VALUE));
        System.out.println(test.mySqrt(1));
        System.out.println(test.mySqrt(4));
        System.out.println(test.mySqrt(10));
        System.out.println(test.mySqrt(65));
        System.out.println(test.mySqrt(Integer.MAX_VALUE));
    }

    public int mySqrt(int x) {
        int l = 0;
        int r = x;
        // Integer.MAX_VALUE 的平方根46340，以这个为基准
        // 也可以下面的值改用long进行计算，就不用考虑越界问题了
        if (r >= 46340) {
            r = 46340;
        }
        while (true) {
            if (l >= r) {
                return r;
            }
            int mid = (l + r) / 2;
            int s = mid * mid;
            if (s == x) {
                return mid;
            }
            if (s < x) {
                int s1 = (mid+1)*(mid+1);
                if (s1 == x) {
                    return mid + 1;
                }
                if (s1 > x) {
                    return mid;
                }
                l = mid + 1;
            }else {
                r = mid;
            }
        }
    }
}
